const db = require('../../lib/conn_oracle')

exports.getLbPersonConfig = async (req,res) => {
    // console.log(req.body)
    let {form } = req.body
    let {pg,username,isExpired} = form

    let resMsg = ""
    let resStatus = 0
    let resDatas = {}
    let reqDatas = []

    let pgWhere = ""
    let usernameWhere = ""
    let usernameLike =  ""
    let isExpiredWhere = ""

    if(pg.length > 0){
        pgWhere = `and u.persongroup = :pg`
        reqDatas.push(pg)
    }else{
        pgWhere = ""
    }

    if(username.length > 0) {
        usernameLike = `%${username}%`
        usernameWhere = `and u.realname like :usernameLike`
        reqDatas.push(usernameLike)
    }else{
        usernameLike = ""
        usernameWhere = ""
    }

    isExpired ? isExpiredWhere = `and p.next_redate <= sysdate` : isExpiredWhere = ""

    let sql = `
                select p.ID 
                    ,p.PERSONID 
                    ,u.realname    
                    ,p.LB_PTYPE
                    ,v.description as vd
                    ,p.LBNUM 
                    ,ls.description as lsd
                    ,p.SERVICE_CYCLE
                    ,p.quantity 
                    ,p.LAST_REDATE  
                    ,p.NEXT_REDATE  
                    ,p.REMARK   
                    ,p.PERSONGROUP
                    ,pg.pgname 
                    ,p.createdate
                from c##wxw.lb_personconfig p 
                inner join c##wxw.vue_xfjcusers u 
                on p.personid = u.personid                
                inner join C##WXW.LB_VALUES v
                on p.lb_ptype = v.value
                and v.cust_type = 'LB_PTYPE'
                inner join C##WXW.LB_LIST ls
                on p.lbnum = ls.lbnum
                inner join c##wxw.persongroup pg
                on p.persongroup = pg.persongroup
                where 1 = 1
                ${pgWhere}
                ${isExpiredWhere}
                ${usernameWhere}
                order by p.persongroup,p.personid,p.lbnum
            `
            // console.log(sql)
    let result = reqDatas.length ? await db.search(sql,reqDatas) : await db.search2(sql)
    resMsg = result.errorNum ? `获取失败,${result}` : `获取成功`
    resStatus = result.errorNum ? 0 : 1
    resDatas = { result }
    res.json({
        msg:resMsg,
        status: resStatus,
        resDatas
    })
}

exports.editLbPersonConfig = async (req,res)=>{
    // console.log(req.body)
    let { type,form } = req.body
    let { ID,PERSONID,LB_PTYPE,LBNUM,SERVICE_CYCLE,QUANTITY,LAST_REDATE,NEXT_REDATE,REMARK,PERSONGROUP } = form
    let reqData = []
    let msgType = ""
    let resMsg = ""
    let resStatus = 0
    let resDatas = {}
    let sql = ""
    if(type === 'add' || type === 'copy'){
        msgType = type === 'add' ? '添加' : '复制'
        sql = `insert into c##wxw.lb_personconfig (ID,PERSONID,LB_PTYPE,LBNUM,SERVICE_CYCLE,QUANTITY,LAST_REDATE,NEXT_REDATE,REMARK,PERSONGROUP)
               values (:ID,:PERSONID,:LB_PTYPE,:LBNUM,:SERVICE_CYCLE,:QUANTITY,to_timestamp(:LAST_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),to_timestamp(:NEXT_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),:REMARK,:PERSONGROUP)
              `
        reqData = [ID,PERSONID,LB_PTYPE,LBNUM,SERVICE_CYCLE,QUANTITY,LAST_REDATE,NEXT_REDATE,REMARK,PERSONGROUP]
        let reqSql = `select * from c##wxw.lb_personconfig where lbnum = :LBNUM and personid = :PERSONID`
        let lbListInfo = await db.search(reqSql,[LBNUM,PERSONID])
        if(lbListInfo.length){
            res.json({
                msg:`新增失败，${PERSONID}的${LBNUM}已存在`,
                status:0
            })
            return
        }
        let noHasLbListSql = `select * from c##wxw.lb_list where lbnum = :LBNUM` 
        let noHasLbListInfo = await db.search(noHasLbListSql,[LBNUM])
        if(!noHasLbListInfo.length){
            res.json({
                msg:`新增失败，${LBNUM}不存在，请先新增劳保明细`,
                status:0
            })
            return
        }
    }
    if(type === 'update'){
        msgType = '更新'
        sql = `update c##wxw.lb_personconfig
               set personid = :PERSONID,
                   LB_PTYPE = :LB_PTYPE,
                   SERVICE_CYCLE = :SERVICE_CYCLE,
                   QUANTITY = :QUANTITY,
                   LAST_REDATE = to_timestamp(:LAST_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),
                   NEXT_REDATE = to_timestamp(:NEXT_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),
                   REMARK = :REMARK,
                   PERSONGROUP = :PERSONGROUP
               where ID = :ID
              `
        reqData = [PERSONID,LB_PTYPE,SERVICE_CYCLE,QUANTITY,LAST_REDATE,NEXT_REDATE,REMARK,PERSONGROUP,ID]
    }
    if(type === 'delete'){
        msgType = '删除'
        sql = `delete from c##wxw.lb_personconfig
               where ID = :ID
              `
        reqData = [ID]
    }

    try{
        let result = await db.writeTab(sql,reqData)
        // console.log(result)
        resMsg = result.errorNum ? `${msgType}失败,${result}` : `${msgType}成功`
        resStatus = result.errorNum ? 0 : 1
        resDatas = { result }
        res.json({
            msg:resMsg,
            status: resStatus,
            resDatas
        })
    }catch(err){
        res.json({
            msg:`${msgType}失败`+err,
            status:0
        })
    }
}

exports.editManyLbPersonConfig = async (req,res)=>{     
    // console.log(req.body)
    let { type,form } = req.body
    let options = {
        autoCommit: true
    }
    let msgType = ""
    let resMsg = ""
    let resStatus = 0
    let resDatas = {}
    let sql = ""
    if(type === 'batchAdd'){
        msgType = '新增'
        sql = `insert into c##wxw.lb_personconfig (ID,PERSONID,LB_PTYPE,LBNUM,SERVICE_CYCLE,QUANTITY,LAST_REDATE,NEXT_REDATE,REMARK,PERSONGROUP)
               values (:ID,:PERSONID,:LB_PTYPE,:LBNUM,:SERVICE_CYCLE,:QUANTITY,to_timestamp(:LAST_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),to_timestamp(:NEXT_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),:REMARK,:PERSONGROUP)
              `
        //检测LB_LIST表中是否存在相应的物资编码
        let needAddLbs = []
        form.forEach(item => {
            item.LBNUM && needAddLbs.push(item.LBNUM)
        });
        // console.log(needAddPgs)
        let lbListSql = `select p.lbnum
                            from c##wxw.lb_list p
                            where p.lbnum in ('${needAddLbs.join("','")}')
                            `
        let lbListInfo = await db.search2(lbListSql)
        let lbnumList = lbListInfo.map(item => item.LBNUM)
        let diff = !lbnumList.length ? needAddLbs : needAddLbs.filter(item => !lbnumList.includes(item))
        if(diff.length){
            res.json({
                msg:`${msgType}失败，物资编码：${diff.join(",")}，不存在，请先新增劳保明细`,
                status:0
            })
            return
        }

        //检测LB_PERSONCONFIG表中是否存在相同的记录
        let lnbAndPIdWhere = ""
        form.forEach((item,index) => {
            lnbAndPIdWhere += `(lbnum = '${item.LBNUM}' and personid = '${item.PERSONID}') or `
            if(index === form.length - 1){
                lnbAndPIdWhere += `(lbnum = '${item.LBNUM}' and personid = '${item.PERSONID}')`
            }
        });
        let lbpcSql = `select * from c##wxw.lb_personconfig where ${lnbAndPIdWhere}`
        let lbPcInfo = await db.search2(lbpcSql)
        // console.log(lbPcInfo)
        msgStr = ""
        lbPcInfo.forEach(item => {msgStr += item.PERSONID + "的" + item.LBNUM + "；"})
        // console.log(msgStr)
        if(lbPcInfo.length){
            res.json({
                msg:`新增失败，${msgStr}均已存在`,
                status:0
            })
            return
        }
    }
    if(type === 'batchUpdate'){
        msgType = '更新'
        sql = `update c##wxw.lb_personconfig
               set PERSONID = :PERSONID,
                   LB_PTYPE = :LB_PTYPE,
                   LBNUM = :LBNUM,
                   SERVICE_CYCLE = :SERVICE_CYCLE,
                   QUANTITY = :QUANTITY,
                   LAST_REDATE = to_timestamp(:LAST_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),
                   NEXT_REDATE = to_timestamp(:NEXT_REDATE,'yyyy-mm-dd hh24:mi:ss.ff'),
                   REMARK = :REMARK,
                   PERSONGROUP = :PERSONGROUP
               where ID = :ID
              `
    }
    if(type === 'batchDel'){
        msgType = '删除'
        sql = `delete from c##wxw.lb_personconfig
               where ID = :ID
              `
    }
    try{
        let result = await db.writeManyTab(sql,form,options)
        resMsg = result.errorNum ? `${msgType}失败,${result}` : `${msgType}成功`
        resStatus = result.errorNum ? 0 : 1
        resDatas = { result }
        res.json({
            msg:resMsg,
            status: resStatus,
            resDatas
        })
    }catch(err){
        res.json({
            msg:`${msgType}失败`+err,
            status:0
        })
    }
}